
var HxBasicGoodsInfoDlg = {
    data: {
        id:"",
        goodsCustomerId: "",
        goodsCustomerName: "",
        goodsName: "",
        goodsNumber: "",
        goodsPcode69: "",
        goodsXcode69: "",
        goodsHelpcode: "",
        goodsSpecs: "",
        goodsBigtype: "",
        goodsBrand: "",
        jibenUnit: "",
        kcUnit: "",
        kcRate: "",
        cgUnit: "",
        cgRate: "",
        pfUnit: "",
        pfRate: "",
        psUnit: "",
        psRate: "",
        anquanNum: "",
        goodsBottom: "",
        goodsLamination: "",
        goodsTraylayer: "",
        goodsSupportvolume: "",
        length: "",
        height: "",
        width: "",
        goodsWeight: "",
        goodsVolume: "",
        goodsChargingCg: "",
        goodsChargingPs: "",
        goodsChargingPf: "",
        goodsWarranty: ""
    }
};
var BasicPutgoodsInfoDlg = {
    data: {
        id:"",
        dictId:"",
        putgoodsCustomerId: "",
        putgoodsOperateName: "",
        putgoodsName: "",
        unitNumber:"",
        unitType:""
    }
};
var list2 = []
var submit = 2
layui.use(['table', 'admin', 'ax','laydate'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var laydate = layui.laydate;

    laydate.render({
        elem:'#startTime'
        ,value:new Date()
    });

    laydate.render({
        elem:'#endTime'
        ,value:new Date()
    });

    /**
     * 出库订单表管理
     */
    var StoreProcurement = {
        tableId: "storeProcurementTable"
    };

    /**
     * 出库订单明细表管理
     */
    var StoreProcurementDetailed = {
        tableId: "storeProcurementDetailedTable"
    };

    /**
     * 初始化表格的列
     */
    StoreProcurement.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', hide: true, title: '主键'},
            {align: 'center', toolbar: '#tableBar', title: '操作', width: 80},
            {field: 'orderState', sort: true, title: '单据状态'},
            {field: 'peisongTime', sort: true, title: '配送日'},
            {field: 'orderOutNumber', sort: true, title: '订单号', width: 160},
            {field: 'xlbRequestOrderType', sort: true, title: 'xlb补货单类型'},
            {field: 'orderType', sort: true, title: '单据类型'},
            {field: 'setUnit', sort: true, title: '发货单位'},
            {field: 'setWarehouse', sort: true, title: '发货仓库'},
            {field: 'getUnit', sort: true, title: '收货客户', width: 140},

            {field: 'goodsNum', sort: true, title: '商品数', totalRowText: '合计：'},
            {field: 'outNum', sort: true, title: '数量', totalRowText: sl.outNum},
            {field: 'zNum', sort: true, title: '整件数量', totalRowText: sl.zNum},
            {field: 'lNum', sort: true, title: '拆零数量', totalRowText: sl.lNum},
            {field: 'outVolume', sort: true, title: '体积', totalRowText: sl.outVolume},
            {field: 'outWeight', sort: true, title: '重量', totalRowText: sl.outWeight},

            {field: 'customerName', sort: true, title: '客户名称'},
            {field: 'createUserName', sort: true, title: '创建人'},
            {field: 'revokeUserName', sort: true, title: '撤销人'},
            {field: 'createTime', sort: true, title: '创建时间'},
            {field: 'revokeTime', sort: true, title: '撤销时间'},
            {field: 'notes', sort: true, title: '备注'},
            {field: 'associationOrder', sort: true, title: '关联单据'},
            {field: 'associationOrderType', sort: true, title: '关联单据类型'},
        ]];
    };

    /**
     * 点击查询按钮
     */
    StoreProcurement.search = function () {
        var queryData = {};
        queryData['timeType'] = $("#timeType").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        queryData['customerId'] = $("#customerId").val();
        queryData['setWarehouseId'] = $("#setWarehouseId").val();
        queryData['getUnits'] = $("#getUnit").val();
        queryData['condition'] = $("#condition").val();
        queryData['orderType'] = $("#orderType").val();
        queryData['goodsNames'] = $("#goodsName").val();

        // $.ajax({
        //     url:Feng.ctxPath + '/storeProcurement/count',
        //     data: queryData, // 将 queryData 作为请求体发送
        //     dataType:"json",   //返回格式为json
        //     async: false,
        //     type:"post",   //请求方式
        //     success:function(data){
        //         sl = data.data
        //     }
        // });

        // 渲染表格
        var tableResult = table.render({
            elem: '#' + StoreProcurement.tableId,
            where: queryData,
            url: Feng.ctxPath + '/storeProcurement/list',
            toolbar: '#toolbarfrom',
            totalRow: true ,//开启合计行
            cellMinWidth: 100,
            cols: StoreProcurement.initColumn(),
            parseData: function(res){ // 数据转换
                return {
                    "code": 0,
                    "msg": res.msg, // 假设原数据中的msg字段存储的是提示信息
                    "count": res.count,
                    "data": $.map(res.data, function(item){ // 假设原数据中的data字段存储的是数据集
                        return {
                            // 假设你想转换的字段是numberField
                            outNum: Number(item.outNum), // 将字符串转换为数字
                            zNum: Number(item.zNum),
                            lNum: Number(item.lNum),
                            // 其他字段保持不变
                            id: item.id,
                            orderOutNumber: item.orderOutNumber,
                            orderState: item.orderState,
                            peisongTime: item.peisongTime,
                            xlbRequestOrderType: item.xlbRequestOrderType,
                            orderType: item.orderType,
                            setWarehouse: item.setWarehouse,
                            getUnit: item.getUnit,
                            customerName: item.customerName,
                            setUnit: item.setUnit,
                            goodsNum: item.goodsNum,
                            outVolume: item.outVolume,
                            outWeight: item.outWeight,

                            createTime: item.createTime,
                            revokeTime: item.revokeTime,
                            notes: item.notes,
                            associationOrder: item.associationOrder,
                            associationOrderType: item.associationOrderType,
                            revokeUserName: item.revokeUserName,
                            createUserName: item.createUserName,
                        };
                    })
                };
            },
            page: true,
            limit: 40,
            height: 410,
        });
        /*table.reload(StoreProcurement.tableId, {
            where: queryData, page: {curr: 1},
             done:function () {
            }
        });*/
    };

    // 批量提交
    $('#btnSubmission').click(function () {
        var checkStatus = table.checkStatus(StoreProcurement.tableId);
        var data2 = checkStatus.data;
        if (data2.length>0) {
            var orders = [];
            var getUnit = ""
            var orderType = ""
            for (var i = 0; i < data2.length; i++) {
                orders.push(data2[i].orderOutNumber);
                if(getUnit == "" || getUnit == null){
                    getUnit = data2[i].getUnit
                } else {
                    if(getUnit != data2[i].getUnit){
                        layer.msg('请选择同一家客户');
                        return
                    }
                }
                if(orderType == "" || orderType == null){
                    orderType = data2[i].orderType
                } else {
                    if(data2[i].orderType != null && data2[i].orderType != ""){
                        if(orderType != data2[i].orderType){
                            layer.msg('请选择同类型订单');
                            return
                        }
                    }
                }
            }
            submit = 2
            layer.open({
                type: 2,
                title: '批量提交',
                area: ['800px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/storeProcurement/tobtnSubmission?orders='+orders,
                end: function () {
                    if(submit == 1){
                        table.reload(StoreProcurement.tableId);
                    }
                }
            });
        } else {
            layer.alert('请至少选中一条数据');
        }
    });

    // 批量提交
    $('#btnSubmission2').click(function () {
        var checkStatus = table.checkStatus(StoreProcurement.tableId);
        var data2 = checkStatus.data;
        if (data2.length>0) {
            var orders = [];
            var getUnit = ""
            var orderType = ""
            for (var i = 0; i < data2.length; i++) {
                orders.push(data2[i].orderOutNumber);
                if(getUnit == "" || getUnit == null){
                    getUnit = data2[i].getUnit
                } else {
                    if(getUnit != data2[i].getUnit){
                        layer.msg('请选择同一家客户');
                        return
                    }
                }
                if(orderType == "" || orderType == null){
                    orderType = data2[i].orderType
                } else {
                    if(data2[i].orderType != null && data2[i].orderType != ""){
                        if(orderType != data2[i].orderType){
                            layer.msg('请选择同类型订单');
                            return
                        }
                    }
                }
            }
            submit = 2
            layer.open({
                type: 2,
                title: '批量提交',
                area: ['800px', '550px'],
                anim: 5,
                content: Feng.ctxPath + '/storeProcurement/tobtnSubmission2?orders='+orders,
                end: function () {
                    if(submit == 1){
                        table.reload(StoreProcurement.tableId);
                    }
                }
            });
        } else {
            layer.alert('请至少选中一条数据');
        }
    });

    //选择订单明细
    table.on('checkbox(' + StoreProcurement.tableId + ')', function(obj){
        var goodsNum = 0
        var outNum = 0
        var outVolume = 0
        if(obj.checked){
            if(obj.type == 'all'){
                var data = table.checkStatus(StoreProcurement.tableId).data
                for (var i = 0; i < data.length; i++) {
                    goodsNum = (parseFloat(goodsNum)+parseFloat(data[i].goodsNum)).toFixed(3)
                    outNum = (parseFloat(outNum)+parseFloat(data[i].outNum)).toFixed(3)
                    outVolume = (parseFloat(outVolume)+parseFloat(data[i].outVolume)).toFixed(3)
                }
                $("#goodsNum").text(goodsNum)
                $("#outNum").text(outNum)
                $("#outVolume").text(outVolume)
            } else if (obj.type == 'one'){
                var data = table.checkStatus(StoreProcurement.tableId).data
                for (var i = 0; i < data.length; i++) {
                    goodsNum = (parseFloat(goodsNum)+parseFloat(data[i].goodsNum)).toFixed(3)
                    outNum = (parseFloat(outNum)+parseFloat(data[i].outNum)).toFixed(3)
                    outVolume = (parseFloat(outVolume)+parseFloat(data[i].outVolume)).toFixed(3)
                }
                $("#goodsNum").text(goodsNum)
                $("#outNum").text(outNum)
                $("#outVolume").text(outVolume)
            }
        } else {
            if(obj.type == 'all'){
                $("#goodsNum").text(0)
                $("#outNum").text(0)
                $("#outVolume").text(0)
            } else if (obj.type == 'one'){
                var data = table.checkStatus(StoreProcurement.tableId).data
                for (var i = 0; i < data.length; i++) {
                    goodsNum = (parseFloat(goodsNum)+parseFloat(data[i].goodsNum)).toFixed(3)
                    outNum = (parseFloat(outNum)+parseFloat(data[i].outNum)).toFixed(3)
                    outVolume = (parseFloat(outVolume)+parseFloat(data[i].outVolume)).toFixed(3)
                }
                $("#goodsNum").text(goodsNum)
                $("#outNum").text(outNum)
                $("#outVolume").text(outVolume)
            }
        }
    });

    // 导入excel
    $('#btnExpimport').click(function () {
        layer.open({
            type: 2,
            title: '出库订单导入',
            area: ['1000px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/storeProcurement/toimportExcel',
            end: function () {
                table.reload(StoreProcurement.tableId);
            }
        });
    });

    //拉取新零帮出库申请单
    $('#pullxlbOutapplicationorder').click(function () {
        submit = 2
        layer.open({
            type: 2,
            title: '拉取新零帮出库申请单',
            area: ['850px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/storeProcurement/topullxlbOutapplicationorder',
            end: function () {
                if(submit == 1){
                    table.reload(StoreProcurement.tableId);
                }
            }
        });
    });
    //拉取新零帮出库申请单
    $('#pulltcslOutapplicationorder').click(function () {
        submit = 2
        layer.open({
            type: 2,
            title: '拉取天财商龙出库申请单',
            area: ['850px', '600px'],
            anim: 5,
            content: Feng.ctxPath + '/storeProcurement/topulltcslOutapplicationorder',
            end: function () {
                if(submit == 1){
                    table.reload(StoreProcurement.tableId);
                }
            }
        });
    });

    //点击选择商品名称
    $('#choiceGoods').click(function () {
        layer.open({
            type: 2,
            title: '选择商品',
            area: ['1000px', '500px'],
            content: Feng.ctxPath + '/hxBasicGoods/toChoiceGoods',
            end: function () {
                $("#goodsName").val(HxBasicGoodsInfoDlg.data.goodsName);//商品名称
            }
        });
    });

    $('#choiceGetUnit').click(function () {
        layer.open({
            type: 2,
            title: '选择单位',
            area: ['1000px', '500px'],
            content: Feng.ctxPath + '/basicPutgoods/tochoiceBasicPutgoods_hx',
            end: function () {
                $("#getUnit").val(BasicPutgoodsInfoDlg.data.putgoodsName);
            }
        });
    });

    /**
     * 弹出添加对话框
     */
    StoreProcurement.openAddDlg = function () {
        window.location.href = Feng.ctxPath + '/storeProcurement/add?page=1&limit=100';
    };
    /**
     * 导出
     */
    StoreProcurement.exportExcel = function () {
        var checkRows = table.checkStatus(StoreProcurement.tableId);
        if (checkRows.data.length > 0) {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        } else {
            var queryData = {};
            queryData['timeType'] = $("#timeType").val();
            queryData['startTime'] = $("#startTime").val();
            queryData['endTime'] = $("#endTime").val();
            queryData['customerId'] = $("#customerId").val();
            queryData['setWarehouseId'] = $("#setWarehouseId").val();
            queryData['getUnits'] = $("#getUnit").val();
            queryData['condition'] = $("#condition").val();
            queryData['orderType'] = $("#orderType").val();
            queryData['goodsNames'] = $("#goodsName").val();
            $.ajax({
                type: "POST",
                url: Feng.ctxPath + "/storeProcurement/listAll",
                dataType:'json',
                data: queryData,
                beforeSend: function () {
                    //弹出加载中
                    index = layer.load(1, {
                        shade: [0.3, '#000'] //0.1透明度的白色背景
                    });
                },
                success: function (data) {
                    checkRows.data = data;
                    table.exportFile(tableResult.config.id, checkRows.data, 'xls');
                    layer.close(index);
                },
                error: function (data) {
                    console.log(data)
                }
            });
        }
    };

    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    StoreProcurement.openEditDlg = function (data) {
        window.location.href = Feng.ctxPath + '/storeProcurement/edit?id=' + data.id+'&page=1&limit=100';
    };

    var sl = {
        outNum:"",
        zNum:"",
        lNum:"",
        outVolume:"",
        outWeight:""
    }

    // $.ajax({
    //     url:Feng.ctxPath + '/storeProcurement/count',
    //     dataType:"json",   //返回格式为json
    //     async: false,
    //     type:"post",   //请求方式
    //     success:function(data){
    //         sl = data.data
    //     }
    // });

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + StoreProcurement.tableId,
        url: Feng.ctxPath + '/storeProcurement/list',
        toolbar: '#toolbarfrom',
        totalRow: true ,//开启合计行
        cellMinWidth: 100,
        cols: StoreProcurement.initColumn()
        ,parseData: function(res){ // 数据转换
            return {
                "code": 0,
                "msg": res.msg, // 假设原数据中的msg字段存储的是提示信息
                "count": res.count,
                "data": $.map(res.data, function(item){ // 假设原数据中的data字段存储的是数据集
                    return {
                        // 假设你想转换的字段是numberField
                        outNum: Number(item.outNum),
                        zNum: Number(item.zNum),
                        lNum: Number(item.lNum),
                        // 其他字段保持不变
                        id: item.id,
                        orderOutNumber: item.orderOutNumber,
                        orderState: item.orderState,
                        peisongTime: item.peisongTime,
                        xlbRequestOrderType: item.xlbRequestOrderType,
                        orderType: item.orderType,
                        setWarehouse: item.setWarehouse,
                        getUnit: item.getUnit,
                        customerName: item.customerName,
                        setUnit: item.setUnit,
                        goodsNum: item.goodsNum,
                        outVolume: item.outVolume,
                        outWeight: item.outWeight,
                        createTime: item.createTime,
                        revokeTime: item.revokeTime,
                        notes: item.notes,
                        associationOrder: item.associationOrder,
                        associationOrderType: item.associationOrderType,
                        revokeUserName: item.revokeUserName,
                        createUserName: item.createUserName,
                    };
                })
            };
        },
        page: true,
        limit: 40,
        height: 410,
    });

    // 批量作废
    $('#btnTovoid').click(function () {
        var checkStatus = table.checkStatus('storeProcurementTable');
        data = checkStatus.data;
        if (data.length>0) {
            var ids = [];
            for (var i = 0; i < data.length; i++) {
                ids.push(data[i].id);
            }
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/storeProcurement/tovoid?ids="+ids, function (data) {
                    Feng.success("作废成功!");
                    table.reload(StoreProcurement.tableId);
                }, function (data) {
                    Feng.error("作废失败!" + data.responseJSON.message + "!");
                });
                ajax.start();
            };
            Feng.confirm("是否作废选中订单?", operation);
        } else {
            layer.alert('请至少选中一条数据');
        }
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        StoreProcurement.search();
    });

    $('#reset').click(function () {
        $("#getUnit").val("")
        $("#condition").val("")
        $("#goodsName").val("")
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        StoreProcurement.openAddDlg();
    });

    // 导出excel
    $('#btnExp').click(function () {
        StoreProcurement.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + StoreProcurement.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            StoreProcurement.openEditDlg(data);
        }
    });

    /**
     * 初始化表格的列
     */
    StoreProcurementDetailed.initColumn = function () {
        return [[
            {field: 'id', hide: true, title: '主键'},
            {align: 'center', toolbar: '#tableBarDetailed', title: '操作', width: 120},
            {field: 'goodsName', sort: true, title: '商品名称', width: 160},
            {field: 'goodsNumber', sort: true, title: '商品编号'},
            {field: 'goodsPcode69', sort: true, title: '商品码'},
            {field: 'goodsSpecs', sort: true, title: '规格'},

            {field: 'unit', sort: true, title: '单位', totalRowText: '合计：'},
            {field: 'psNum', sort: true, title: '数量', totalRow: true},
            {field: 'goodsWeight', sort: true, title: '重量'},
            {field: 'outWeight', sort: true, title: '应出重量', totalRow: true},
            {field: 'goodsVolume', sort: true, title: '体积'},
            {field: 'outVolume', sort: true, title: '应出体积', totalRow: true},
            {field: 'goodsPrice', sort: true, title: '单价'},
            {field: 'outMoney', sort: true, title: '金额', totalRow: true},
            {field: 'jibenNum', sort: true, title: '基本数量', totalRow: true},
            {field: 'detailedDate', sort: true, title: '生产日期'},
            {field: 'notes', sort: true, title: '备注'},
        ]];
    };

    // 单击行事件
    table.on('row(' + StoreProcurement.tableId + ')', function (obj) {
        var data = obj.data;
        $('div[lay-id="' + StoreProcurement.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
        $('div[lay-id="' + StoreProcurement.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
        storeProcurement(data);
    });

    function storeProcurement(data){
        var orderOutNumber;
        if (data!=null) {
            orderOutNumber = data.orderOutNumber;
        } else {
            orderOutNumber = '0';
        }
        // 渲染商品明细表格
        var tableResult = table.render({
            elem: '#' + StoreProcurementDetailed.tableId,
            url: Feng.ctxPath + '/storeProcurementDetailed/list?orderOutNumber=' + orderOutNumber,
            page: true,
            limit: 30,
            height: 400,
            toolbar: '#toolbarfromDetailed',
            cellMinWidth: 100,
            totalRow: true ,//开启合计行
            cols: StoreProcurementDetailed.initColumn()
        });

        /**
         * 点击查询按钮
         */
        StoreProcurementDetailed.search = function () {
            var queryData = {};
            queryData['condition'] = $("#condition2").val();
            table.reload(StoreProcurementDetailed.tableId, {
                where: queryData, page: {curr: 1},
                done:function () {
                    // 搜索按钮点击事件
                    $('#btnSearchDetailed').click(function () {
                        StoreProcurementDetailed.search();
                    });
                    $('#btnAddDetailed').click(function () {
                        StoreProcurementDetailed.addDetailed();
                    });
                }
            });
        };

        StoreProcurementDetailed.addDetailed = function () {
            layer.open({
                type: 2,
                title: '明细录入',
                area: ['1050px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/storeProcurementDetailed/add?orderOutNumber=' + data.orderOutNumber,
                end: function () {
                    storeProcurement(data);
                }
            });
        };

        // 工具条点击事件
        table.on('tool(' + StoreProcurementDetailed.tableId + ')', function (obj) {
            var data2 = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'editDetailed') {
                StoreProcurementDetailed.openEditDlg(data2);
            } else if (layEvent === 'deleteDetailed') {
                StoreProcurementDetailed.onDeleteItem(data2);
            }
        });

        // 修改按钮点击事件
        StoreProcurementDetailed.openEditDlg = function (data2) {

            layer.open({
                type: 2,
                title: '明细修改',
                area: ['1050px', '750px'],
                anim: 5,
                content: Feng.ctxPath + '/storeProcurementDetailed/edit?id='+data2.id+'&page=1&limit=100',
                end: function () {
                    storeProcurement(data);
                }
            });
        };

        // 删除按钮点击事件
        StoreProcurementDetailed.onDeleteItem = function (data2) {
            var operation = function () {
                var ajax = new $ax(Feng.ctxPath + "/storeProcurementDetailed/delete", function (data2) {
                    Feng.success("删除成功!");
                    storeProcurement(data);
                }, function (data) {
                    Feng.error("删除失败!" + data2.responseJSON.message + "!");
                });
                ajax.set("id", data2.id);
                ajax.start();
            };
            Feng.confirm("是否删除?", operation);
        };

        // 搜索按钮点击事件
        $('#btnSearchDetailed').click(function () {
            StoreProcurementDetailed.search();
        });

        $('#btnAddDetailed').click(function () {
            StoreProcurementDetailed.addDetailed();
        });
    }






});
